package com.lin.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Cookie: 用键值对形式保存用户信息 一个cookie在客户端的限制是3k<br>
 *      会话性Cookie: cookie只会保留在客户端内存中, 关闭浏览器cookie失效<br>
 *      持久性Cookie: cookie会保存在本地(硬盘), 直到生命周期结束或者用户主动删除<br>
 *          如果将生命收起设置为0或负数, 和会话性Cookie一样, 关闭浏览器cookie失效<br>
 */
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        // 获取cookie
        Cookie[] cookies = req.getCookies();
        PrintWriter writer = resp.getWriter();

        // 判断cookie是否存在
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("lastLoginTime")) {
                    // 将时间字符串转换为日期格式
                    try {
                        long lastLoginTime = Long.parseLong(URLDecoder.decode(cookie.getValue(), "UTF-8"));
                        Date date = new Date(lastLoginTime);
                        // 创建 SimpleDateFormat 对象并指定日期格式
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        // 格式化日期
                        String formattedDate = dateFormat.format(date);
                        writer.write("lastLoginTime: " + formattedDate + "\n");
                        System.out.println("lastLoginTime: " + formattedDate);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            writer.write("this is your first travel, cookie is null");
            System.out.println("this is your first travel, cookie is null");
        }
        // 添加cookie
        Cookie cookie = new Cookie("lastLoginTime", String.valueOf(System.currentTimeMillis()));
        cookie.setMaxAge(-1);
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
